package com.lagou.rabbitmq.mq.listener;

import com.lagou.rabbitmq.dao.GoodDao;
import com.lagou.rabbitmq.dao.OrdersDao;
import com.lagou.rabbitmq.pojo.Orders;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.IOException;

@Component
public class OrderListener {

    @Resource
    private GoodDao goodDao;
    @Resource
    private OrdersDao ordersDao;

    @Transactional
    @RabbitListener(queues = "queue.delayed")
    public void onMessage(Message message, Channel channel) throws IOException {
        System.out.println("接收到消息，订单ID为：" + new String(message.getBody(), message.getMessageProperties().getContentEncoding()));
        Integer ordersId = Integer.valueOf(new String(message.getBody()));
        Orders orders = ordersDao.findById(ordersId).get();
        if (orders.getState() == 0) {
            orders.setState(2);
            ordersDao.save(orders);
            goodDao.inventoryAddById(orders.getGoodId());
            System.out.println("订单未支付:" + ordersId);
        } else {
            System.out.println("订单已支付:" + ordersId);
        }
        // 消息确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
